#ifndef UPLOAD_DATABASE_H
#define UPLOAD_DATABASE_H

#include <QDateTime>
#include <QDebug>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QString>
#include <QThread>
#include <QVariantMap>
#include <QVector>

struct UploadRecord {
    int id;
    QString deviceId;      // 设备ID (如"IP1")
    QString serverIP;      // 服务器IP
    quint16 serverPort;    // 服务器端口
    QString dataContent;   // 上传的数据内容
    qint64 dataSize;       // 数据大小（字节）
    QString status;        // 状态：成功/失败
    QString errorMessage;  // 错误信息（如果失败）
    QDateTime uploadTime;  // 上传时间
    qint64 responseTime;   // 响应时间（毫秒）

    UploadRecord() : id(-1), serverPort(0), dataSize(0), responseTime(0) {}

    UploadRecord(const QString &deviceId, const QString &ip, quint16 port, const QString &data,
                 const QString &status, const QString &error = "")
        : id(-1),
          deviceId(deviceId),
          serverIP(ip),
          serverPort(port),
          dataContent(data),
          dataSize(data.toUtf8().size()),
          status(status),
          errorMessage(error),
          uploadTime(QDateTime::currentDateTime()),
          responseTime(0)
    {
    }

    bool isSuccess() const { return status == "成功"; }

    QString getStatusText() const { return isSuccess() ? "✅ 成功" : "❌ 失败"; }
};

class UploadDatabase
{
public:
    // 初始化上传记录表
    static void initUploadTable();

    // 记录管理
    static bool addUploadRecord(const UploadRecord &record);
    static int addUploadRecordAndGetId(const UploadRecord &record);  // 新增：返回记录ID
    static bool updateUploadStatus(int recordId, const QString &status, const QString &error = "");
    static bool updateResponseTime(int recordId, qint64 responseTime);

    // 查询记录
    static QVector<UploadRecord> getUploadRecords(int limit = 100);
    static QVector<UploadRecord> getUploadRecordsByDevice(const QString &deviceId, int limit = 50);
    static QVector<UploadRecord> getUploadRecordsByDateRange(const QDateTime &startTime,
                                                             const QDateTime &endTime);
    static UploadRecord getUploadRecordById(int id);

    // 分页查询
    static int getTotalUploadRecords(const QDate &date = QDate());
    static QVector<QVariantMap> queryUploadRecordsByPage(int page, int pageSize,
                                                         const QDate &date = QDate());
    static QVector<QVariantMap> queryUploadRecordsByDate(const QDate &date);

    // 统计功能
    static int getTotalUploadCount();
    static int getSuccessUploadCount();
    static int getFailedUploadCount();
    static int getUploadCountByDevice(const QString &deviceId);
    static double getSuccessRate();
    static double getSuccessRateByDevice(const QString &deviceId);

    // 数据清理
    static bool deleteOldRecords(int daysToKeep = 30);
    static bool clearAllRecords();

    // 最近状态
    static UploadRecord getLastUploadRecord(const QString &deviceId);
    static QVector<UploadRecord> getRecentFailedRecords(int count = 10);

private:
    // 禁止实例化
    UploadDatabase() = delete;
    ~UploadDatabase() = delete;
    UploadDatabase(const UploadDatabase &) = delete;
    UploadDatabase &operator=(const UploadDatabase &) = delete;

    static UploadRecord queryToUploadRecord(const QSqlQuery &query);

    // 获取线程安全的数据库连接
    static QSqlDatabase getThreadSafeDatabase();
};

#endif  // UPLOAD_DATABASE_H
